package cn.xjt.gaoji;

/**
 * 测试生产者，消费者问题 2：信号灯法
 * 标志位解决
 * @author xujiangtao
 * @create 2020-08-02-13:11
 */
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new actor(tv).start();
        new watcher(tv).start();
    }
}
//生产者->演员
class actor extends Thread{
    TV tv;
    public actor(TV tv)
    {
        this.tv=tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                if(i%2==0)
                {
                    tv.play("抖音:记录美好生活");
                    System.out.println(i);
                }else{
                    tv.play("快乐大本营");
                    System.out.println(i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//消费者->观众
class watcher extends Thread{
    TV tv;
    public watcher(TV tv)
    {
        this.tv=tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                tv.watch("观众");
                System.out.println(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//产品->Tv
class TV{
    String video;
//    String Watchername;
    boolean flag = true;
    //演员表演，观众等待 T
    //观众观看，演员等待 F
    //表演方法
    public synchronized void play(String vidio) throws InterruptedException {
        //判断如果是true，则表演节目
        if(flag)
        {
            System.out.println("演员表演了->"+vidio);
            Thread.sleep(1000);
            //通知观众观看
            this.notifyAll();   //通知观众观看节目
            this.video=vidio;
            flag=!this.flag;
        }else { //否则，等待观众观看
            this.wait();
        }
    }
    public synchronized void watch(String watchername) throws InterruptedException {
        //判断如果为flase，则观众观看节目
        if(!flag)
        {
            System.out.println(watchername+"观看了"+video);
            Thread.sleep(1000);
            this.notifyAll();
            flag=!flag;
        }else{  //否则等待，直到表演者表演完，再继续观看
            this.wait();
        }
    }
}

